package com.powerbank.user.controller;

import com.powerbank.common.result.Result;
import com.powerbank.common.utils.JwtUtils;
import com.powerbank.user.dto.UserLoginDTO;
import com.powerbank.user.dto.UserRegisterDTO;
import com.powerbank.user.service.AuthService;
import com.powerbank.user.vo.UserInfoVO;
import com.powerbank.user.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;

/**
 * 用户认证控制器
 */
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 发送验证码
     */
    @PostMapping("/send-code")
    public Result<Void> sendVerifyCode(@RequestParam @NotBlank(message = "手机号不能为空") 
                                       @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
                                       String phone) {
        boolean success = authService.sendVerifyCode(phone);
        return success ? Result.success("验证码发送成功", (Void) null) : Result.error("验证码发送失败");
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<UserLoginVO> register(@RequestBody @Valid UserRegisterDTO registerDTO) {
        UserLoginVO loginVO = authService.register(registerDTO);
        return Result.success("注册成功", loginVO);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody @Valid UserLoginDTO loginDTO) {
        UserLoginVO loginVO = authService.login(loginDTO);
        return Result.success("登录成功", loginVO);
    }

    /**
     * 刷新令牌
     */
    @PostMapping("/refresh")
    public Result<UserLoginVO> refreshToken(@RequestParam @NotBlank(message = "刷新令牌不能为空") String refreshToken) {
        UserLoginVO loginVO = authService.refreshToken(refreshToken);
        return Result.success("令牌刷新成功", loginVO);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        String token = extractToken(request);
        if (token != null) {
            Long userId = jwtUtils.getUserIdFromToken(token);
            authService.logout(userId);
        }
        return Result.success("登出成功", (Void) null);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/user-info")
    public Result<UserInfoVO> getCurrentUserInfo(HttpServletRequest request) {
        String token = extractToken(request);
        if (token == null) {
            return Result.error("Token不能为空");
        }
        
        Long userId = jwtUtils.getUserIdFromToken(token);
        UserInfoVO userInfo = authService.getCurrentUserInfo(userId);
        return Result.success(userInfo);
    }

    /**
     * 修改密码
     */
    @PostMapping("/change-password")
    public Result<Void> changePassword(@RequestParam @NotBlank(message = "旧密码不能为空") String oldPassword,
                                       @RequestParam @NotBlank(message = "新密码不能为空") String newPassword,
                                       HttpServletRequest request) {
        String token = extractToken(request);
        if (token == null) {
            return Result.error("Token不能为空");
        }

        Long userId = jwtUtils.getUserIdFromToken(token);
        boolean success = authService.changePassword(userId, oldPassword, newPassword);
        return success ? Result.success("密码修改成功", (Void) null) : Result.error("密码修改失败");
    }

    /**
     * 找回密码
     */
    @PostMapping("/reset-password")
    public Result<Void> resetPassword(@RequestParam @NotBlank(message = "手机号不能为空") 
                                      @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") 
                                      String phone,
                                      @RequestParam @NotBlank(message = "验证码不能为空") String verifyCode,
                                      @RequestParam @NotBlank(message = "新密码不能为空") String newPassword) {
        boolean success = authService.resetPassword(phone, verifyCode, newPassword);
        return success ? Result.success("密码重置成功", (Void) null) : Result.error("密码重置失败");
    }

    /**
     * 从请求中提取JWT Token
     */
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}